<template>
  <div class="gy-view">
    <el-tabs v-model="activeName" style="padding: 10px 0;" @tab-click="handleClick">
      <el-tab-pane label="总预算" name="XMJFLY_ZYS"></el-tab-pane>
      <el-tab-pane label="纵向" name="XMJFLY_ZX" v-if="budget_from.includes('XMJFLY_ZX')"></el-tab-pane>
      <el-tab-pane label="横向" name="XMJFLY_HX" v-if="budget_from.includes('XMJFLY_HX')"></el-tab-pane>
      <el-tab-pane label="自筹" name="XMJFLY_ZC" v-if="budget_from.includes('XMJFLY_ZC')"></el-tab-pane>
    </el-tabs>
    <div class="budget-table-all" v-if="activeName == 'XMJFLY_ZYS'">
      <div v-for="(item, index) in budget_from" :key="index">
        <span>{{ activeObj[item] }}</span>
        <vxe-table style="margin-top: 10px;" height="260" border resizable show-overflow :data="getDeptTableData(item)"
          size="mini" ref="myVxeTable" show-footer :footer-method="footerMethod"
          :merge-footer-items="[{ row: 0, col: 0, rowspan: 2, colspan: 2 }]">
          <vxe-column type="seq" width="60" fixed="left"></vxe-column>
          <vxe-column field="class_funds" title="科目名称" max-width="100" fixed="left"></vxe-column>
          <vxe-column v-for="(column, index) in deptList" :key="index" :field="column.id" :title="column.name">
            <template #default="{ row }">
              <span>{{ deptTotal(row, column, item) }}</span>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <el-empty description="暂无数据" v-if="!budget_from.length"></el-empty>
    </div>
    <div v-else-if="loadingTbale">
      <div v-for="(dept, index) in deptList" :key="index">
        <vxe-button status="primary" content="选择科目" size="mini" @click="showSelectSubject(dept)"
          v-if="isEdit" style="margin-right: 10px;"></vxe-button>
        <!-- <span class="name">{{ dept.name }}</span> -->
        <div class="table-box">
          <vxe-table height="260" border resizable show-overflow :data="getTableData(dept)" style="margin-top: 10px;"
            :edit-config="{ trigger: 'click', mode: 'row', showIcon: false, enabled: isEdit }" size="mini">
            <vxe-column type="seq" width="60" fixed="left"></vxe-column>
            <vxe-column align="left" field="class_funds" title="科目名称" max-width="100" fixed="left"></vxe-column>
            <vxe-column align="left" field="pro_member_org_name" title="承制部门" max-width="100" fixed="left"></vxe-column>
            <vxe-column field="total" title="科目合计（元）" max-width="100" fixed="left" align="right">
              <template #default="{ row }">
                <span>{{ total(row) }}</span>
              </template>
            </vxe-column>
            <vxe-column v-for="(item, index) in getColumnData(dept)" :field="item.pl_pro_year" :key="index"
              :title="item.pl_pro_year" :edit-render="{ enabled: isEdit }" align="right">
              <template #header>
                <span>{{ item.pl_pro_year }}</span>
                <vxe-button type="text" status="primary" icon="vxe-icon-delete" @click="showDelYear(item)"
                  v-if="isEdit"></vxe-button>
                <vxe-button type="text" status="primary" icon="vxe-icon-edit" @click="showEditYear(item)"
                  v-if="isEdit"></vxe-button>
              </template>
              <template #default="{ row }">
                <span v-if="row.budgetAccount[getEditIndex(row, item)]">{{ row.budgetAccount[getEditIndex(row,
                  item)].year_budget }}</span>
              </template>
              <template #edit="{ row }">
                <vxe-input v-if="row.budgetAccount[getEditIndex(row, item)]"
                  v-model="row.budgetAccount[getEditIndex(row, item)].year_budget" type="float" step="1" maxlength="12"
                  clearable @change="setFormData"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column title="操作" width="100" fixed="right" v-if="isEdit">
              <template #default="{ row }">
                <vxe-button @click="showDelSubject(dept, row)" size="mini">删除</vxe-button>
              </template>
            </vxe-column>
          </vxe-table>
          <vxe-button style="margin-top: 10px;" type="text" icon="vxe-icon-add" @click="showAddYear(dept)"
            v-if="isEdit"></vxe-button>
        </div>
      </div>
    </div>
    <el-dialog :title="'新增'" :visible.sync="dialogFormVisible" v-if="dialogFormVisible">
      <el-form :model="yearForm" :rules="rules" ref="ruleForm">
        <el-form-item label="年度" prop="pl_pro_year">
          <el-date-picker value-format="yyyy" size="mini" v-model="yearForm.pl_pro_year" type="year" style="width: 160px"
            placeholder="选择年">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="saveYear" size="mini">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template> 
<script>

export default {
  name: "PLANS",
  data() {
    return {
      yearColumnList: [], // 年度
      budgetList: [], // 科目
      // 来源
      activeName: 'XMJFLY_ZYS',
      budget_from: [],
      activeObj: {
        XMJFLY_ZYS: '总预算',
        XMJFLY_ZX: '纵向',
        XMJFLY_HX: '横向',
        XMJFLY_ZC: '自筹',
      },
      loadingTbale: true,
      yearList: [],

      dialogFormVisible: false,
      yearForm: {
        pl_pro_year: ''
      },
      rules: {
        pl_pro_year: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
      },
      isEdit: false,
      deptList: []
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    handleClick() {
      this.loadingTbale = false
      setTimeout(() => {
        this.loadingTbale = true
      }, 10)
    },
    // 初始化 通过自动化获取数据 并且构建可编辑数据
    async init() {
      this.isEdit = await window.customFieldService.isFieldEditable('pl_pro_budgrt')
      let _this = this
      // 字段改变事件
      window.eventService.onEvent('field-change', async () => {
        let records = await window.customFieldService.getRecord()
        if (records.budget_from.length !== _this.budget_from.length) {
          this.activeName = 'XMJFLY_ZYS'
        }
        _this.budget_from = records.budget_from
        _this.getFundsDept(records.project_leader)
      })
      // 字段重置事件
      window.eventService.onEvent('record-reload', async () => {
        _this.loadingTbale = false
        setTimeout(async () => {
          let records = await window.customFieldService.getRecord()
          if (records.pl_pro_budgrt) {
            _this.initData(records)
            _this.loadingTbale = true
          }
        }, 100)
      })
      // 初始化进来
      let records = await window.customFieldService.getRecord()
      this.budget_from = records.budget_from
      this.getFundsDept(records.project_leader)
      this.initData(records)
    },
    // 获取负责人部门
    async getFundsDept(project_leader) {
      let deptList = await window.systemService.callAutomatic({
        automaticId: 'project_funds_owner_dept',
        args: [project_leader]
      })
      this.deptList = deptList.returnValue
    },
    initData(records) {
      let yearList = []
      let budgetList = []
      records.pl_pro_budgrt.forEach((item) => {
        // 构建年度
        if (item.pl_pro_year) {
          let isEmpty = yearList.findIndex((yearItem) => {
            return item.pl_pro_year_id == yearItem.pl_pro_year_id && item.budget_source_id == yearItem.budget_source_id && item.pro_member_org_id == yearItem.pro_member_org_id
          })
          if (isEmpty == -1) {
            yearList.push({
              pl_pro_year: item.pl_pro_year,
              pl_pro_year_id: item.pl_pro_year_id,
              pro_member_org_id: item.pro_member_org_id,
              pro_member_org_name: item.pro_member_org_name,
              budget_source_id: item.budget_source_id,
              budget_source_name: item.budget_source_name
            })
          }
        }
        // 构建科目
        if (item.class_funds) {
          let isEmpty = budgetList.findIndex((yearItem) => {
            return item.budget_template_id == yearItem.budget_template_id && item.budget_source_id == yearItem.budget_source_id && item.pro_member_org_id == yearItem.pro_member_org_id
          })
          if (isEmpty == -1) {
            budgetList.push({
              pl_pro_year: item.pl_pro_year,
              pl_pro_year_id: item.pl_pro_year_id,
              budget_template_id: item.budget_template_id,
              class_funds: item.class_funds,
              pro_member_org_id: item.pro_member_org_id,
              pro_member_org_name: item.pro_member_org_name,
              budget_source_id: item.budget_source_id,
              budget_source_name: item.budget_source_name,
              budgetAccount: records.pl_pro_budgrt.filter((findItem) => {
                return item.budget_template_id == findItem.budget_template_id && item.budget_source_id == findItem.budget_source_id && item.pro_member_org_id == findItem.pro_member_org_id
              }).map((mapItem) => {
                return {
                  pl_pro_year: mapItem.pl_pro_year,
                  pl_pro_year_id: mapItem.pl_pro_year_id,
                  pro_member_org_id: mapItem.pro_member_org_id,
                  pro_member_org_name: mapItem.pro_member_org_name,
                  project_id: mapItem.project_id,
                  project_id_name: mapItem.project_id_name,
                  budget_source_id: mapItem.budget_source_id,
                  budget_source_name: mapItem.budget_source_name,
                  year_budget: mapItem.year_budget
                }
              })
            })
          }
        }
      })
      this.yearColumnList = yearList
      this.budgetList = budgetList
    },
    // 过滤表体
    getTableData(dept) {
      return this.budgetList.filter((item) => {
        return item.pro_member_org_id == dept.id && item.budget_source_id == this.activeName
      })
    },
    // 过滤表头
    getColumnData(dept) {
      return this.yearColumnList.filter((item) => {
        return item.pro_member_org_id == dept.id && item.budget_source_id == this.activeName
      })
    },
    // 科目
    showSelectSubject(dept) {
      let list = this.budgetList.filter((item) => {
        return item.pro_member_org_id == dept.id && item.budget_source_id == this.activeName
      })
      window.systemService.callAutomatic({
        automaticId: 'budget_choose',
        args: [list.map((item) => item.budget_template_id)]
      }).then(async (result) => {
        result.returnValue.forEach((item) => {
          item.budget_source_name = this.activeObj[this.activeName]
          item.budget_source_id = this.activeName
          item.pro_member_org_id = dept.id
          item.pro_member_org_name = dept.name
          this.budgetList.push(JSON.parse(JSON.stringify(item)))
        })
        let deptYear = this.yearColumnList.filter((item) => {
          return item.pro_member_org_id == dept.id && item.budget_source_id == this.activeName
        })
        this.budgetList.forEach((item) => {
          if (!item.budgetAccount) {
            item.budgetAccount = []
          }
          if (item.pro_member_org_id == dept.id && item.budget_source_id == this.activeName) {
            deptYear.forEach((yearItem) => {
              let pushItem = JSON.parse(JSON.stringify(yearItem))
              pushItem.year_budget = ''
              item.budgetAccount.push(pushItem)
            })
          }
        })
        this.setFormData()
      })
    },
    showDelSubject(dept, row) {
      //调用确认提示
      window.systemService.confirm({
        title: '此操作将永久删除，是否继续?'
      }).then(confirm => {
        if (!confirm) {
          return;
        }
        this.budgetList = this.budgetList.filter((item) => {
          return !(item.pro_member_org_id == dept.id && item.budget_source_id == this.activeName && item.budget_template_id == row.budget_template_id)
        })
        this.setFormData()
      });
    },
    // 年份
    showAddYear(dept) {
      this.yearForm.pl_pro_year = ''
      this.yearForm.isType = 'add'
      this.yearForm.pro_member_org_id = dept.id
      this.yearForm.pro_member_org_name = dept.name
      this.yearForm.budget_source_id = this.activeName
      this.yearForm.budget_source_name = this.activeObj[this.activeName]
      this.dialogFormVisible = true
    },
    showDelYear(item) {
      //调用确认提示
      window.systemService.confirm({
        title: '此操作将永久删除，是否继续?'
      }).then(confirm => {
        if (!confirm) {
          return;
        }
        this.yearColumnList = this.yearColumnList.filter((yearItem) => {
          return item.pl_pro_year_id != yearItem.pl_pro_year_id
        })
        // 删除科目里面年份
        this.budgetList.forEach((budgetItem) => {
          if (budgetItem.budgetAccount) {
            budgetItem.budgetAccount = budgetItem.budgetAccount.filter((accountItem) => {
              return accountItem.pl_pro_year_id != item.pl_pro_year_id
            })
          }
        })
        this.setFormData()
        this.loadingTbale = false
        setTimeout(() => {
          this.loadingTbale = true
        }, 10);
      });

    },
    showEditYear(item) {
      this.yearForm = JSON.parse(JSON.stringify(item))
      this.yearForm.isType = 'edit'
      this.dialogFormVisible = true
    },
    saveYear() {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) {
          return
        }
        let yearForm = JSON.parse(JSON.stringify(this.yearForm))
        let yearList = this.yearColumnList.filter((item) => {
          return item.budget_source_id == this.activeName
        })
        if (yearForm.isType == 'add') {
          yearForm.pl_pro_year_id = this.yearColumnList.length + new Date().getTime() + ''
          let isEmpty = yearList.findIndex((item) => {
            return item.pl_pro_year == yearForm.pl_pro_year && item.pro_member_org_id == yearForm.pro_member_org_id
          })
          if (isEmpty != -1) {
            this.$message('已存在选择年份')
            return
          }
          this.yearColumnList.push(yearForm)
          this.budgetList.forEach((item) => {
            if (!item.budgetAccount) {
              item.budgetAccount = []
            }
            if (item.pro_member_org_id == yearForm.pro_member_org_id && item.budget_source_id == this.activeName) {
              let pushItem = JSON.parse(JSON.stringify(yearForm))
              pushItem.year_budget = ''
              item.budgetAccount.push(pushItem)
            }
          })
        } else {
          let isEdit = true
          yearList.forEach((item) => {
            if (item.pro_member_org_id == yearForm.pro_member_org_id && item.pl_pro_year == yearForm.pl_pro_year && item.pl_pro_year_id != yearForm.pl_pro_year_id) {
              isEdit = false
            }
          })
          if (!isEdit) {
            this.$message('已存在选择年份')
            return
          }
          this.yearColumnList.forEach((item) => {
            if (item.pl_pro_year_id == yearForm.pl_pro_year_id) {
              item.pl_pro_year = yearForm.pl_pro_year
            }
          })
        }
        this.dialogFormVisible = false
        this.setFormData()
      });
    },
    // 获取编辑 下标
    getEditIndex(row, year) {
      let index = row.budgetAccount.findIndex((item) => {
        return item.pl_pro_year_id == year.pl_pro_year_id
      })
      return index == -1 ? '' : index
    },
    // 设置表单字段
    setFormData() {
      let list = []
      if (this.budgetList.length) {
        // 科目下年度 如果有循环年度，没有追加自己
        this.budgetList.forEach((item) => {
          if (item.budgetAccount.length) {
            item.budgetAccount.forEach((accountItem) => {
              let pushItem = JSON.parse(JSON.stringify(accountItem))
              pushItem.budget_template_id = item.budget_template_id
              pushItem.class_funds = item.class_funds
              list.push(pushItem)
            })
          } else {
            let pushItem = JSON.parse(JSON.stringify(item))
            pushItem.pl_pro_year = ''
            pushItem.pl_pro_year_id = ''
            list.push(pushItem)
          }
        })
        // 构建之后，判断没有科目年度，追加为空
        this.yearColumnList.forEach((yearItem) => {
          let isEmpty = list.findIndex((item) => {
            return yearItem.pl_pro_year_id == item.pl_pro_year_id && yearItem.pro_member_org_id == item.pro_member_org_id && yearItem.budget_source_id == item.budget_source_id
          })
          if (isEmpty == -1) {
            list.push(yearItem)
          }
        })
      } else {
        list = this.yearColumnList
      }
      window.customFieldService.setFieldValue({
        field: 'pl_pro_budgrt',
        value: list
      })
    },
    total(row) {
      if (row.budgetAccount.length) {
        let total = 0
        row.budgetAccount.forEach((item) => {
          total += +item.year_budget
        })
        return total
      } else {
        return 0
      }
    },
    // 获取总预算表体
    getDeptTableData(type) {
      return this.budgetList.filter((item) => item.budget_source_id == type)
    },

    // 总预算科目合计
    subjectTotal(row, type) {
      console.log(row, type)
    },
    // 总预算部门合计
    deptTotal(row, column) {
      if (row.pro_member_org_id == column.id && row.budgetAccount.length) {
        let total = 0
        row.budgetAccount.forEach((item) => {
          total += +item.year_budget
        })
        return total
      } else {
        return 0
      }
    },
    // 总预算表尾合并
    footerMethod({ columns, data }) {
      const footerData = [
        columns.map((column, _columnIndex) => {
          if (_columnIndex === 0) {
            return '合计'
          }
          if (_columnIndex === 1) {
            return '合计'
          }
          let total = 0
          data.forEach((item) => {
            if (item.pro_member_org_id == column.field) {
              item.budgetAccount.forEach((accountItem) => {
                total += +accountItem.year_budget
              })
            }
          })
          return total
        })
      ]
      return footerData
    },
    isYearShow() {
      let fList = this.yearList.filter((item) => {
        return item.budget_source_id == this.activeName
      })
      if (fList.length < 10) {
        return true
      } else {
        return false
      }
    }
  }
}
</script>
<style>
.gy-view {
  background: #fff;
  height: 100%;
}

.el-tabs__active-bar {
  width: 42px !important;
}

.table-box {
  display: flex;
  align-items: flex-start;
}

.table-box .vxe-table {
  flex: 1;
  width: 200px;
  margin-bottom: 10px;
}

.budget-table-all {}
</style>